package com.johnsoncs.gio.lastcall.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.gwt.user.datepicker.client.DatePicker;


public class NotClever implements EntryPoint {
	Date countingTo = null;
	@Override
	public void onModuleLoad() {
		DatePicker dp = new DatePicker();
		dp.addValueChangeHandler(new ValueChangeHandler<Date>() {
			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				if(event.getValue().before(new Date())) {
					Window.alert("Please select a future date");
				} else {
					countingTo = event.getValue();
				}
			}
		});
		Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
			@Override
			public boolean execute() {
				if (countingTo!= null) {
					History.newItem(getText(), false);
				}
				return true;
			}
		}, 990);
		RootPanel.get().add(dp);
		dp.setSize("100%", "100%");
		
	}
	
	String getText() {
		Date now = new Date();
		StringBuilder sb = new StringBuilder();
		
		
		long diff = countingTo.getTime() - now.getTime();
		long hours = (diff % 86400000) / 3600000;
		long minutes = (diff % 3600000) / 60000;
		long seconds = (diff % 60000) / 1000;
		sb.append(CalendarUtil.getDaysBetween(now, countingTo)).append("_days_").append(hours).append("_hours_").append(minutes).append("_minutes_").append(seconds).append("_seconds");
		return sb.toString();
		
	}
}
